﻿using Microsoft.AspNetCore.Mvc;
using star_questionnair.Services;
using star_questionnair.Services.impl;

namespace star_questionnair.Controllers;

[Route("textAnalysis")]
[ApiController]
public class TextAnalysisController : ControllerBase
{
    private readonly IWordCloudService _wordCloudService;

    // 构造函数注入 WordCloudService
    public TextAnalysisController(IWordCloudService wordCloudService)
    {
        _wordCloudService = wordCloudService;
    }

    // 问题词频
    [HttpGet("wordFrequencies/{questionId}")]
    public async Task<ActionResult<Dictionary<string, int>>> GenerateWordFrequencies(int questionId)
    {
        var result = await _wordCloudService.GenerateWordFrequencies(questionId);
        if (result == null)
            return Ok(new { message = "No words found." });
        return Ok(new { success = true, data = result });
    }

    // 问题平均文本量
    [HttpGet("averageText/{questionId}")]
    public async Task<ActionResult> GetAverageOfQuestion(int questionId)
    {
        try
        {
            var result = await _wordCloudService.GetAverageWordOfQuestion(questionId);
        
            // 判断是否有结果返回
            if (result.HasValue)
            {
                return Ok(new { success = true, data = result.Value });
            }

            // 没有数据的情况
            return Ok(new { success = false, message = "No words found." });
        }
        catch (Exception ex)
        {
            // 处理异常，返回错误信息
            return StatusCode(500, new { success = false, message = "An error occurred.", details = ex.Message });
        }
    }


    // 根据性别生成问题词频
    [HttpGet("wordFrequencies/gender/{questionId}")]
    public async Task<ActionResult<Dictionary<bool, Dictionary<string, int>>>> GenerateWordFrequenciesByGender(int questionId)
    {
        var result = await _wordCloudService.GenerateGenderSpecificWordCloud(questionId);
        if (result == null)
            return Ok(new { message = "No words found." });
        return Ok(new { success = true, data = result });
    }
}